Java JavaScript Python C# C C++ Go Kotlin PHP Swift R Ruby TypeScript Scala SQL Perl rust VisualBasic Matlab Julia

Class in oops

Inheritance & subclass

Certainly! In Java, inheritance is a mechanism that allows a new class to be based on an existing class. The new class is called the subclass or child class, and the existing class is called the superclass or parent class. The subclass inherits the properties and methods of the superclass, and it can also add its own properties and methods. In Java, inheritance is achieved by using the extends keyword. Here is an example of how to create a subclass in Java:
example for creating a subclass public class Main{ public static void main(String args[]){ Dog obj=new Dog(); obj.bark(); obj.eat(); } } public class Animal { public void eat() { System.out.println("The animal is eating."); } } public class Dog extends Animal { public void bark() { System.out.println("The dog is barking."); } }

Output

The dog is barking. The animal is eating.
In this example, we have defined a superclass called Animal with one method (eat). We have also defined a subclass called Dog that extends the Animal class and adds one method (bark). To create an object of the Dog class, we can use the following code:
creating an object Dog myDog = new Dog(); myDog.eat(); // inherited from Animal class myDog.bark(); // defined in Dog class
This code creates a new Dog object called myDog, calls the eat method (inherited from the Animal class), and calls the bark method (defined in the Dog class).

  📌TAGS

★Class ★ Method ★ Object ★ java ★ oops ★ inheritance

Tutorials